//index.js
//获取应用实例
const app = getApp()
const { getAllProductByLabel, collectionListByType, getAllPlatform, queryHotWords } = require('../../api/url.js')

Page({
  data: {
    showModal: false,//是否显示授权模态框
    carousels: [],//轮播图数据
    sysInfo: null,//系统信息
    hotPage: 1,//热销商品页码
    hotSize: 10,//热销商品每页数量
    hotList: [],//热卖列表
    isShowCartModal: false,//是否显示加入购物车模态框
    cartGoodsId: '',//购物车模态框商品id
    cartCount: 0,//购物车模态框商数量
    count: 0,//商品选择购买的数量
    hotKeyWords: [],//热搜关键字
    hotLoadOver: false,//是否加载完热卖商品
    heiderHeight: 0,//头部高度
    supermes: [],//优选搭档商品
    isIPX: false,//是否是iPhoneX
  },
  /**
   * @method
   * @desc 获取热搜关键字
   */
  getHotWords() {
    let that = this
    wx.request({
      url: queryHotWords,
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        page: 1,
        size: 9999
      },
      success(res) {
        if (res.data.code === 0) {
          let temList = res.data.response.cont.list
          temList.length = 5
          that.setData({
            hotKeyWords: temList
          })
        }
      }
    })
  },
  /**
   * @method
   * @desc 打开购物车模态框
   */
  openCartModal(e) {
    let that = this
    that.setData({
      cartGoodsId: e.currentTarget.dataset.item.fId,
      cartCount: 1
    })
    that.setData({
      isShowCartModal: true
    })
  },
  openCartModal2(e) {
    let that = this
    let item = e.currentTarget.dataset.item
    if (item.fTotalCount > 0) {
      that.setData({
        cartGoodsId: item.fId,
        cartCount: item.count
      })
      that.setData({
        isShowCartModal: true
      })
    } else {
      wx.showToast({
        title: '库存不足',
        icon: 'none'
      })
    }

  },
  /**
   * @method
   * @desc 关闭加入购物车模态框
   */
  closeCartModal() {
    let that = this
    that.setData({
      isShowCartModal: !that.data.isShowCartModal
    })
  },
  /**
   * @method
   * @desc 跳转轮播详情
   */
  goToDetail(e) {
    let that = this
    wx.navigateTo({
      url: '/pages/goodsDetail/goodsDetail?id=' + e.currentTarget.dataset.item.fId,
    })
  },
  /**
   * 跳转商品列表页
   */
  goGoodsList(e) {
    switch (e.currentTarget.dataset.type) {
      case 'shopClassfy':
        wx.navigateTo({
          url: `/pages/goodsList/goodsList?id=${e.currentTarget.dataset.id}&type=${e.currentTarget.dataset.type}`,
        })
        break
      case 'search':
        wx.navigateTo({
          url: `/pages/goodsList/goodsList?keyWord=${e.currentTarget.dataset.item.fKeyword}&type=${e.currentTarget.dataset.type}`,
        })
        break
      case 'inputSearch':
        wx.navigateTo({
          url: `/pages/goodsList/goodsList?keyWord=${e.detail.value}&type=search`,
        })
        break
    }

  },
  /**
   * @method
   * 加载热销商品
   * @param page,size,fLabel
   */
  loadHotGoods(page, size, fLabel) {
    let that = this
    wx.request({
      url: getAllProductByLabel,
      data: {
        page: page,
        size: size,
        fLabel: fLabel
      },
      success(res) {
        if (res.data.code === 0) {
          that.setData({
            hotPage: that.data.hotPage + 1
          })
          if (res.data.response.cont.list && res.data.response.cont.list.length > 0) {
            let temHotList = res.data.response.cont.list
            if (temHotList.length < size) {
              that.setData({
                hotLoadOver: true
              })
            }
            temHotList.forEach(val => {
              if (val.fMainPicture) {//设置商品显示图片
                val.img = app.globalData.imageBaseUrl + val.fMainPicture
              } else {
                //默认图片地址
              }
              if (val.fFixedPrice) {
                val.priTxt = val.fFixedPrice.toFixed(2)
              }
              val.count = 1
              val.totalPriTxt = val.priTxt
            })
            that.setData({
              hotList: that.data.hotList.concat(temHotList)
            })
          } else if (res.data.response.cont.list && res.data.response.cont.list.length == 0) {
            that.setData({
              hotList: that.data.hotList
            })
            that.setData({
              hotLoadOver: true
            })
            wx.showToast({
              title: '已加载完商品',
              icon: 'none'
            })
          } else {
            wx.showToast({
              title: '热卖商品异常',
              icon: 'none'
            })
          }
        } else {
          wx.showToast({
            title: '获取热卖失败',
            icon: 'none'
          })
        }

      }
    })
  },
  /**
   * @method 
   * @desc 获取随机颜色值
   */
  getRandomColor(min, max) {
    return Math.floor(Math.random() * (max - min) + min)
  },
  /**
   * @method
   * @desc 加载轮播图
   */
  loadCarousels() {
    let that = this
    wx.request({
      url: getAllProductByLabel,
      data: {
        page: 1,
        size: 9999,
        fLabel: 5
      },
      success(res) {
        if (res.data.code === 0) {
          if (res.data.response.cont.list && res.data.response.cont.list.length > 0) {
            let temHotList = res.data.response.cont.list
            temHotList.forEach(val => {
              // if(val.){}
              if (val.fMainPicture) {//设置商品显示图片
                val.img = app.globalData.imageBaseUrl + val.fMainPicture
              } else {
                //默认图片地址
              }
              if (val.fFixedPrice) {
                val.priTxt = val.fFixedPrice.toFixed(2)
              }
              val.count = 1
              val.totalPriTxt = val.priTxt
              val.color = `rgb(${that.getRandomColor(100, 200)},${that.getRandomColor(50, 255)},${that.getRandomColor(50, 255)})`
            })
            that.setData({
              carousels: temHotList
            })
          } else {
            that.setData({
              carousels: []
            })
          }
        } else {
          wx.showToast({
            title: '获取热卖失败',
            icon: 'none'
          })
        }

      }
    })
  },
  /**
   * @method
   * @desc 加载优选搭档
   */
  loadSupermes() {
    let that = this
    wx.request({
      url: getAllProductByLabel,
      data: {
        page: 1,
        size: 9999,
        fLabel: 4
      },
      success(res) {
        if (res.data.code === 0) {
          if (res.data.response.cont.list && res.data.response.cont.list.length > 0) {
            let temHotList = res.data.response.cont.list
            temHotList.forEach(val => {
              if (val.fMainPicture) {//设置商品显示图片
                val.img = app.globalData.imageBaseUrl + val.fMainPicture
              } else {
                //默认图片地址
              }
              if (val.fFixedPrice) {
                val.priTxt = val.fFixedPrice.toFixed(2)
              }
              val.count = 1
              val.totalPriTxt = val.priTxt
            })
            that.setData({
              supermes: temHotList
            })
          } else {
            that.setData({
              carousels: []
            })
          }
        } else {
          wx.showToast({
            title: '获取热卖失败',
            icon: 'none'
          })
        }

      }
    })
  },
  /**
   * @method
   * @desc 加载店铺分类
   */
  loadShopClassify(page, size) {
    let that = this
    wx.request({
      url: getAllPlatform,
      data: {
        page,
        size
      },
      success(res) {
        if (res.data.code === 0) {
          let temList = res.data.response.cont.list
          if (temList && temList.length > 0) {
            temList.forEach(val => {
              val.img = app.globalData.imageBaseUrl + val.fImage
            })
          }
          that.setData({
            shopClassifyList: temList
          })
        } else {
          wx.showToast({
            title: '店铺分类异常',
            icon: 'none'
          })
        }
      }
    })
  },
  /**
   * @method
   * 授权回调
   */
  settingCB(res) {
    let that = this
    if (res.detail.detail.errMsg === 'getUserInfo:ok') {
      app.globalData.wxUserInfo = res.detail.detail.userInfo
      wx.showLoading({
        title: '用户登录',
        mask: true
      })
      app.getUserInfo().then(res => {
        wx.hideLoading()
        that.setData({
          showModal: false
        })
        if (res.data.code === 0) {
          //做其它操作
          app.loadCollections(0, 9999, app.globalData.userInfo.loginname)
        } else {
          wx.showToast({
            title: '用户登录失败',
            icon: 'none'
          })
        }
      })
    } else {
      that.setData({
        showModal: false
      })
    }
  },
  /**
   * @method
   * @desc 关闭模态框
   */
  closeModal() {
    let that = this
    that.setData({
      showModal: false
    })
  },
  /**
   * @method
   * @desc 获取icom联系电话
   */
  getContact() {
    wx.showModal({
      title: 'Tips',
      content: '联系我们？',
      success(res) {
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: '15198854094',
          })
        }
      }
    })
  },
  onLoad: function () {
    let that = this
    that.setData({
      sysInfo: app.globalData.systemInfo,
      isIPX: app.globalData.isIPX
    })
  },
  onShow() {
    let that = this
    app.userLogin().then(res => {
      wx.hideLoading()
      if (res === 'noAuthorize') {
        that.setData({
          showModal: true
        })
      } else if (res === 'success') {
        that.setData({
          showModal: false
        })
        //做其它请求
      } else if (res === 'fail') {
        that.setData({
          showModal: false
        })
        wx.showToast({
          title: '注册用户失败',
          icon: 'none'
        })
      }
    })
    that.loadHotGoods(that.data.hotPage, that.data.hotSize, 3)
    that.loadShopClassify(1, 9999)
    that.getHotWords()
    that.loadCarousels()
    that.loadSupermes()
  },
  onPullDownRefresh() {
    let that = this
    that.setData({
      showModal: false,//是否显示授权模态框
      carousels: [],//轮播图数据
      sysInfo: null,//系统信息
      hotPage: 1,//热销商品页码
      hotSize: 10,//热销商品每页数量
      hotList: [],//热卖列表
      isShowCartModal: false,//是否显示加入购物车模态框
      cartGoodsId: '',//购物车模态框商品id
      cartCount: 0,//购物车模态框商数量
      count: 0,//商品选择购买的数量
      hotKeyWords: [],//热搜关键字
      hotLoadOver: false,//是否加载完热卖商品
      supermes: [],//优选搭档商品
    })
    that.setData({
      sysInfo: app.globalData.stystemInfo
    })
    that.loadHotGoods(that.data.hotPage, that.data.hotSize, 3)
    that.loadShopClassify(1, 9999)
    that.getHotWords()
    that.loadCarousels()
    that.loadSupermes()
    wx.stopPullDownRefresh()
  },
  onReachBottom() {
    let that = this
    if (!that.data.hotLoadOver) {
      that.loadHotGoods(that.data.hotPage, that.data.hotSize, 3)
    } else {
      wx.showToast({
        title: '已加载完所有商品',
        icon: 'none'
      })
    }

  },
  onReady(){
    let that=this
    //获取头部高度
    setTimeout(()=>{
      wx.createSelectorQuery().select('.header').boundingClientRect(res => {
        console.log(res)
        that.setData({
          heiderHeight: res.bottom,
        })
      }).exec()
    },300)
  }
})
